package com.juzhencms.apps.busi.web;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.FileUtil;
import com.juzhencms.apps.base.common.util.ObjectUtil;
import com.juzhencms.apps.base.common.util.WebUtil;
import com.juzhencms.apps.busi.service.TemplateService;

import lombok.extern.slf4j.Slf4j;


@Controller
@RequestMapping("/templateFile")
@Slf4j
public class TemplateFileController  extends BaseController{
	@Autowired
	private TemplateService templateService;
	
	@RequestMapping(value="/gridlistData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String gridlistData(HttpServletRequest request){
		
		try {
			List fileList=new ArrayList();
			
			int siteId=0;
			if(request.getParameter("site_id")!=null && !request.getParameter("site_id").toString().trim().equals("0") && !request.getParameter("site_id").toString().trim().equals("")) {
				siteId=Integer.parseInt(request.getParameter("site_id").toString().trim());
			}
			
			String code=request.getParameter("code");
			String file_type=request.getParameter("file_type");
			String page_type=request.getParameter("page_type");
			
			
			String module=request.getParameter("module");
			
			
			
			if(request.getParameter("action")!=null && request.getParameter("action").toString().trim().equals("select_menu_template")) {
				file_type="page";
				Map site=this.getCommonService().getJdbcDao().queryRow("select template_code from "+DBTable.site+" where id=? and del_flag=0", new Object[] {siteId});
				if(site!=null && site.get("template_code")!=null) {
					code=site.get("template_code").toString();
				}
				
				if(module!=null && module.equals("all")) {
					module="";
				}
				
				//默认情况下采用栏目对应的功能
				if(module!=null && module.equals("default")) {
					module=request.getParameter("menu_module");
				}
				
			}
			//log.info("siteId:"+siteId);
			//log.info("code:"+code);
			
			//如果存在站点ID参数及模板code参数
			if(code!=null && !code.trim().equals("")) {
				code=code.trim();
				
						
				
				Map template=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.template+" where code=? and del_flag=0 order by id asc limit 0,1", new Object[] {code});
				if(template!=null) {
					//读取模板配置文件
					//File configFile=new File(Config.getUploadFilePath()+"/templates/"+template.get("template_path")+"/config.json");
					//Map templateConfigData=JSON.parseObject(FileUtil.getTextContents(configFile.getAbsolutePath(),"UTF-8"),LinkedHashMap.class,Feature.OrderedField);
					Map templateConfigData=templateService.getConfig(template.get("template_path").toString());
					if(templateConfigData!=null) {
						Map filesMap=(Map)templateConfigData.get("files");
						if(filesMap!=null) {
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							for(Object key : filesMap.keySet()) {  	  
								List tmpFileList=(List)filesMap.get(key);
								if(tmpFileList!=null && tmpFileList.size()>0) {
									for(int i=0;i<tmpFileList.size();i++) {
										Map tmpFile=(Map)tmpFileList.get(i);
										
										Map file=new HashMap();
										file.put("name", tmpFile.get("name"));
										file.put("file_type", key);
										file.put("file", tmpFile.get("file"));
										file.put("module", tmpFile.get("module"));
										file.put("page_type", tmpFile.get("pageType"));
										
										//查询是否存在编辑记录，如果存在则记录编辑时间
										int templateSiteId=0;
										if(template.get("template_type").toString().equals("2")) {
											templateSiteId=siteId;
										}
										Map dbFileData=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.templateFile+" where template_code=? and site_id=? and file=? order by id asc limit 0,1", new Object[] {code,templateSiteId,tmpFile.get("file")});
										if(dbFileData!=null) {
											file.put("update_time", sdf.format(dbFileData.get("update_time")));
										}
										fileList.add(file);
									}	
									
								}
							} 
						}
					}
						
				}			
			}
			
			//查询列表数据
			
			List dataList=new ArrayList();
			
			if(fileList!=null) {
				for(int i=0;i<fileList.size();i++) {
					Map tmp=(Map)fileList.get(i);
					
					if(file_type!=null && !file_type.trim().equals("")) {
						file_type=file_type.trim();
						if(!file_type.equals(tmp.get("file_type").toString())) {
							continue;
						}
					}
					if(page_type!=null && !page_type.trim().equals("")) {
						page_type=page_type.trim();
						if(!page_type.equals(tmp.get("page_type").toString())) {
							continue;
						}
					}
					if(module!=null && !module.trim().equals("")) {
						module=module.trim();
						if(!module.equals(tmp.get("module").toString())) {
							continue;
						}
					}
					
					dataList.add(tmp);
				}
			}
			
			
			
					
					
			int recordsTotal=dataList.size();
			
			
			//拼装返回的数据
			Map data=new HashMap();
			data.put("data", dataList.toArray());
			data.put("itemsCount", recordsTotal);
			
			
			return WebUtil.resultString(data,request);
		
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			Map data=new HashMap();
			data.put("result", 0);
			data.put("msg", "读取模板失败");
			return WebUtil.resultString(data,request);
		}
		
		
	}
	
	@RequestMapping(value="/detailData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String detailData(HttpServletRequest request){
		
		String code=request.getParameter("code");
		String file=request.getParameter("file");
		String siteId=request.getParameter("site_id");
		
		//判断数据库中是否存在，若数据库中不存在，则读取模板文件
		Map data=new HashMap();
		Map record=null;
		if(siteId!=null) {
			record=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.templateFile+" where del_flag=0 and template_code=? and file=? and site_id=? order by id asc limit 0,1",new Object[]{code,file,siteId});	
		}
				
				
		if(record==null) {
			//读取文件
			Map template=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.template+" where code=? and site_id=0 and del_flag=0 limit 0,1", new Object[] {code});
			
			
			//读取模板文件获取文件内容
			record=new HashMap();
			record.put("template_code", code);
			record.put("file", file);
			record.put("site_id", siteId);
			try {
				record.put("content", FileUtil.getTextContents(templateService.getTemplatesPath()+"/"+template.get("template_path")+"/"+file, "UTF-8"));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.error("读取模板文件"+file+"出错",e);
			}
		}else {
			//如果存在修改记录，则展示版本信息
			Map lastHistory=this.getDataHistoryService().getLastValidVersion(DBTable.templateFile, Integer.parseInt(record.get("id").toString()));
			if(lastHistory!=null) {
				if(lastHistory.get("params")!=null) {
					/*//使用最新的版本字段替换掉当前主表字段进行显示
					Map param=JSON.parseObject(lastHistory.get("params").toString(),Map.class);
					if(param!=null) {
						for(Object key : param.keySet()) {
							if(param.get(key)!=null) {
								record.put(key, param.get(key));
							}
						}
					}*/
					lastHistory.remove("params");
				}
				data.put("lastHistory", lastHistory);
			}
		}	
		data.put("data", record);
		return WebUtil.resultString(data,request);
		
	}
	
	@RequestMapping(value="/save",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String save(HttpServletRequest request) throws IOException{
		
		
		//System.out.println(request.getParameter("data"));
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		String templateCode=data.get("template_code").toString();
		int siteId=Integer.parseInt(data.get("site_id").toString());
		
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		
		//敏感词检查
		String sensitiveKeywords=this.filterSensitiveKeywords(DBTable.templateFile, data);
		if(sensitiveKeywords!=null) {
			Map result=new HashMap();
			result.put("result", 0);
			result.put("id", id);
			result.put("msg", "内容中包含敏感关键词:<font style='color:#F00'>"+sensitiveKeywords+"</font>,请修改后再提交");
			return WebUtil.resultString(result,request);
		}
		
		
		
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		if(id==null || id.equals("")){
			Map template=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.template+" where code=? and del_flag=0 order by id asc limit 0,1", new Object[] {templateCode});
			//读取模板文件获取字段信息
			Map templateConfigData=templateService.getConfig(template.get("template_path").toString());
			
			if(templateConfigData!=null) {
				Map filesMap=(Map)templateConfigData.get("files");
				if(filesMap!=null) {
					for(Object key : filesMap.keySet()) {  	  
						List tmpFileList=(List)filesMap.get(key);
						if(tmpFileList!=null && tmpFileList.size()>0) {
							for(int i=0;i<tmpFileList.size();i++) {
								Map tmpFile=(Map)tmpFileList.get(i);
								
								String fileName=tmpFile.get("file").toString();
								if(data.get("file").toString().equals(fileName)) {
									data.put("name", tmpFile.get("name"));
									data.put("file_type", key);
									data.put("page_type", tmpFile.get("pageType"));
									data.put("module", tmpFile.get("module"));
									break;
								}
							}	
							
						}
					} 
				}
			}
			
			//只有在复制模板的情况下存储站点id到模板文件
			if(template.get("template_type")!=null && template.get("template_type").toString().equals("2")) {
				data.put("site_id", siteId);
			}
			
			data.put("create_time", sdf.format(date));
			data.put("update_time", sdf.format(date));
			//this.getCommonService().getJdbcDao().addObj(DBTable.templateFile, data);
			
			//手动向版本表增加一条记录，用以恢复至修改前的版本
			Map bakRecord=ObjectUtil.copy(data, HashMap.class);
			bakRecord.put("content",FileUtil.getTextContents(templateService.getTemplatesPath()+"/"+template.get("template_path")+"/"+data.get("file").toString(), "UTF-8"));//设置审核状态为已通过
			
			Map bakHistoryRecord=new HashMap();
			bakHistoryRecord.put("data_type", DBTable.templateFile);
			//读取文件内容
			bakHistoryRecord.put("check_status", 1);//设置审核状态为已通过
			bakHistoryRecord.put("create_time",new Date() );
			bakHistoryRecord.put("update_description", "修改前自动备份");
			bakHistoryRecord.put("title", data.get("name"));
			bakHistoryRecord.put("params", JSON.toJSONString(bakRecord));
			int historyId=this.getCommonService().getJdbcDao().addObj(DBTable.dataHistory, bakHistoryRecord);
			
			id=""+this.getDataHistoryService().saveData(DBTable.templateFile, data);
			data.put("id", id);
			
			//修改备份版本的数据ID
			this.getCommonService().getJdbcDao().updateSql("update "+DBTable.dataHistory+" set data_id=? where id=?", new Object[] {data.get("id"),historyId});
			
			
		}else{
			data.put("update_time", sdf.format(date));
			this.getDataHistoryService().saveData(DBTable.templateFile, data);
			//this.getCommonService().getJdbcDao().updateObj(DBTable.templateFile, data, "id");
		}
		
		//更新到模板表的更新时间字段
		this.getCommonService().getJdbcDao().updateSql("update "+DBTable.template+" set update_time=now() where code=? and site_id=? and del_flag=0", new Object[] {templateCode,siteId});
		
		
		Map result=new HashMap();
		result.put("result", 1);
		result.put("msg", "保存成功");
		
		
		return WebUtil.resultString(result,request);
		
	}
	
	
	
	
	
}
